package co.chuangdian.oflauncher.uc;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import co.chuangdian.oflauncher.MainActivity;
import co.chuangdian.oflauncher.R;
import co.chuangdian.oflauncher.uc.FolderAppsGridView.AppsGridViewAdapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView.LayoutParams;
import cn.onekit.*;
import cn.onekit.android.*;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import uc.IconView;

public class FolderAppsAdapter extends BaseAdapter implements AppsGridViewAdapter {
	List<PackageInfo> apps = new ArrayList<PackageInfo>();

	final int COLUMNS = 3;
	private int mHidePosition = -1;
	Context context;
	public int MARGIN_TOP;
	android.content.pm.PackageManager packageManager;
	FolderAppsGridView appsGridView;
	int folderIndex;
	JSONArray folders;
	JSONObject folder;

	public void setData(List<PackageInfo> apps) {
		this.apps = apps;
		//
		Resources res = context.getResources();
		setHeader(res.getIdentifier(folder.optString("icon"), "drawable", context.getPackageName()),
				folder.optString("name"));
		notifyDataSetChanged();
	}

	public void setFolderIndex(int folderIndex) {
		this.folderIndex = folderIndex;
		folders = JSON.parses((String) CONFIG.get("folders"));
		folder = folders.optJSONObject(folderIndex);
	}

	public FolderAppsAdapter(Context context, FolderAppsGridView appsGridView) {
		this.context = context;
		this.appsGridView = appsGridView;
		packageManager = context.getPackageManager();
	}

	@Override
	public int getCount() {
		return apps.size() + COLUMNS;
	}

	@Override
	public Object getItem(int position) {
		position -= COLUMNS;
		return apps.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	ImageView iconImageView;
	EditText titleEditText;
	TextView titleTextView;
	Button coverButton;
	int iconResID;
	String title;

	public void setHeader(int iconResID, String title) {
		this.iconResID = iconResID;
		this.title = title;
	}

	public void setHeaderMode(boolean mode) {
		appsGridView.isHeaderPress = mode;
		coverButton.setVisibility(mode ? View.VISIBLE : View.GONE);
		titleTextView.setVisibility(mode ? View.GONE : View.VISIBLE);
		titleEditText.setVisibility(mode ? View.VISIBLE : View.GONE);
		if (OnModeChangeListener != null) {
			OnModeChangeListener.onModeChange(mode);
		}
	}

	public interface OnCoverChangeListener {
		void onCoverChange();
	}

	public void setOnCoverChangeListener(OnCoverChangeListener OnCoverChangeListener) {
		this.OnCoverChangeListener = OnCoverChangeListener;
	}

	OnCoverChangeListener OnCoverChangeListener;

	public interface OnModeChangeListener {
		void onModeChange(boolean mode);
	}

	public void setOnModeChangeListener(OnModeChangeListener OnModeChangeListener) {
		this.OnModeChangeListener = OnModeChangeListener;
	}

	OnModeChangeListener OnModeChangeListener;

	@SuppressLint({ "ViewHolder", "InflateParams" })
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		if (position < COLUMNS) {
			FrameLayout viewGroup = new FrameLayout(context);
			viewGroup.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, MARGIN_TOP));
			viewGroup.setOnLongClickListener(new OnLongClickListener() {

				@Override
				public boolean onLongClick(View v) {
					setHeaderMode(true);
					return true;
				}

			});
			//
			switch (position) {
			case 0: {
				iconImageView = new ImageView(context);
				FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ACTIVITY.dp2px(50),
						ACTIVITY.dp2px(30));
				layoutParams.bottomMargin = ACTIVITY.dp2px(10);
				layoutParams.gravity = Gravity.END | Gravity.BOTTOM;
				iconImageView.setLayoutParams(layoutParams);
				iconImageView.setImageResource(iconResID);
				viewGroup.addView(iconImageView);
				break;
			}
			case 1: {
				titleTextView = new TextView(context);
				FrameLayout.LayoutParams titleTextViewLayoutParams = new FrameLayout.LayoutParams(
						LayoutParams.MATCH_PARENT, ACTIVITY.dp2px(30));
				titleTextViewLayoutParams.bottomMargin = ACTIVITY.dp2px(10);
				titleTextViewLayoutParams.gravity = Gravity.BOTTOM;
				titleTextView.setLayoutParams(titleTextViewLayoutParams);
				titleTextView.setText(title);
				titleTextView.setTextSize(20);
				titleTextView.setGravity(Gravity.CENTER_VERTICAL);
				titleTextView.setTextColor(Color.WHITE);
				viewGroup.addView(titleTextView);
				//
				titleEditText = new EditText(context);
				FrameLayout.LayoutParams titleEditTextLayoutParams = new FrameLayout.LayoutParams(
						LayoutParams.MATCH_PARENT, ACTIVITY.dp2px(40));
				titleEditTextLayoutParams.bottomMargin = ACTIVITY.dp2px(5);
				titleEditTextLayoutParams.gravity = Gravity.BOTTOM;
				titleEditText.setLayoutParams(titleEditTextLayoutParams);
				titleEditText.setText(title);
				titleEditText.setSingleLine();
				titleEditText.setOnEditorActionListener(new OnEditorActionListener() {

					@Override
					public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
						if (actionId == EditorInfo.IME_ACTION_DONE) {
							try {
								String title = v.getText().toString();
								titleTextView.setText(title);
								folder.put("name", title);
								CONFIG.set("folders", folders);
								APP.hideKeyboard(v);
								setHeaderMode(false);
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
						return false;
					}

				});
				titleEditText.setTextSize(20);
				titleEditText.setGravity(Gravity.CENTER_VERTICAL);
				viewGroup.addView(titleEditText);
				//
				coverButton = new Button(context);
				FrameLayout.LayoutParams coverButtonLayoutParams = new FrameLayout.LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
				coverButtonLayoutParams.gravity = Gravity.CENTER;
				coverButton.setLayoutParams(coverButtonLayoutParams);
				// coverButton.setBackgroundColor(Color.TRANSPARENT);
				coverButton.setText(R.string.home_header_cover);
				coverButton.setTextSize(20);
				coverButton.setTextColor(Color.WHITE);
				coverButton.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						DIALOG.photo(new CALLBACK<Bitmap>() {

							@Override
							public void run(boolean isError, Bitmap image) {
								if (isError) {
									return;
								}
								String cover = folder.optString("cover");
								File coverFile = FSO.photos(cover);
								FSO.saveImage(image, coverFile.getPath());
								if (OnCoverChangeListener != null) {
									OnCoverChangeListener.onCoverChange();
								}
							}
						});
					}
				});
				viewGroup.addView(coverButton);
				//
				break;
			}
			case 2: {
				setHeaderMode(false);
				break;
			}
			default:
				break;
			}
			//

			return viewGroup;
		}
		position -= COLUMNS;
		//
		IconView iconView = new IconView(context);
		iconView.setLayoutParams(
				new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, ACTIVITY.dp2px(IconView.HEIGHT)));
		PackageInfo app = apps.get(position);
		Drawable icon = app.applicationInfo.loadIcon(packageManager);
		String title = MainActivity.getAlias(app);
		iconView.setData(icon, title);
		if (position == mHidePosition) {
			iconView.setVisibility(View.INVISIBLE);
		}
		return iconView;
	}

	@Override
	public void reorderItems(int oldPosition, int newPosition) {
		oldPosition -= 3;
		newPosition -= 3;
		if (oldPosition < 0 || oldPosition >= apps.size()) {
			return;
		}
		if (newPosition < 0 || newPosition >= apps.size()) {
			return;
		}
		PackageInfo temp = apps.get(oldPosition);
		if (oldPosition < newPosition) {
			for (int i = oldPosition; i < newPosition; i++) {
				Collections.swap(apps, i, i + 1);
			}
		} else if (oldPosition > newPosition) {
			for (int i = oldPosition; i > newPosition; i--) {
				Collections.swap(apps, i, i - 1);
			}
		}

		apps.set(newPosition, temp);
	}

	@Override
	public void setHideItem(int hidePosition) {
		hidePosition -= COLUMNS;
		this.mHidePosition = hidePosition;
		notifyDataSetChanged();
	}

}
